package org.jeecg.modules.controller;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.service.IDiyProfessorInfoService;
import org.jeecg.modules.vo.ExportProfessorInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ZhangHaoyu
 * @description
 * @date 2020/9/3 22:46
 */
@Controller
@RequestMapping("/org/exportProfessor")
public class ExportProfessorInfoController {
    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;
    @Autowired
    private IDiyProfessorInfoService diyProfessorInfoService;


    @PostMapping("exportPDF")
    @ResponseBody
    public Result<String> exportPDF(@RequestBody ExportProfessorInfo professorInfo, HttpServletResponse response) throws IllegalAccessException, NoSuchFieldException, UnsupportedEncodingException {
        // 创建集合保存需要填写到pdf中的数据
        List<String> list = new ArrayList<>();
        // 处理日期格式
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // 利用反射获取对象的属性，进行数据的处理
        Class clazz = professorInfo.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();

        for (Field field : declaredFields) {
            if ("String".equals(field.getType().getSimpleName())) {
                //根据属性名获取属性值
                String value = getFieldValueByFieldName(field.getName(), professorInfo);
                // 处理空指针
                if (value == null || "".equals(value)) {
                    list.add("");
                } else {
                    // 判断是否是申报类别
                    if ("professorDeclareCategory".equals(field.getName())){
                        StringBuffer sb = new StringBuffer();
                        // 处理申报类别
                        String[] ids = value.split(",");
                        for (int i = 0; i < ids.length; i++) {
                            // 字符串拼接
                            sb.append(diyProfessorInfoService.getDeclareCategoryName(ids[i]));
                            // 拼接,
                            if (i<ids.length-1){
                                sb.append(",");
                            }
                        }
                        value = sb.toString();
                    }else if ("professorMajor".equals(field.getName())){
                        if ("".equals(value) || value==null){
                            value = "";
                        }else {
                            value = diyProfessorInfoService.getMajorNameById(value);
                            if (value==null || "".equals(value))
                                value="";
                        }
                    }
                    list.add(value);
                }
            } else if ("Integer".equals(field.getType().getSimpleName())) {
                // 设置可以使用private
                field.setAccessible(true);
                Integer obj = (Integer) field.get(professorInfo);
                // 处理空指针异常
                if (obj == null) {
                    list.add("");
                } else if ("professorSex".equals(field.getName())) {
                    // 判断属性名是否是sex
                    // 修正性别，并放入list中
                    list.add(obj == 1 ? "男" : "女");
                }

            } else if ("Date".equals(field.getType().getSimpleName())) {
                // 设置可以使用private
                field.setAccessible(true);
                Date date = (Date) field.get(professorInfo);
                // 处理空指针异常
                if (date == null) {
                    list.add("");
                } else {
                    // 处理日期格式
                    String dateStr = df.format(date);
                    list.add(dateStr);
                }
            }
        }
        response.setContentType("application/pdf;charset=utf-8");
        // 调用业务层方法根据list集合导出pdf
        String filePath = diyProfessorInfoService.exportPDF(list);
        Result<String> result = new Result<>();
        result.setMessage(filePath);
        return result;
    }

    /**
     * 根据前端传入的文件名下载对应的pdf
     * @param filePath 文件名
     * @return 文件流
     * @throws FileNotFoundException
     */
    @GetMapping("downloadPDF")
    @ResponseBody
    public ResponseEntity<Object> downloadPDF(@RequestParam("filePath") String filePath) throws FileNotFoundException {
        String fileName = uploadpath+File.separator+filePath;
        File file = new File(fileName);
        InputStreamResource resource = new InputStreamResource(new FileInputStream((file)));

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition",String.format("attachment;filename=\"%s\"",file.getName()));
        headers.add("Cache-Control","no-cache,no-store,must-revalidate");
        headers.add("Pragma","no-cache");
        headers.add("Expires","0");

        ResponseEntity<Object> responseEntity = ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/pdf;charset=utf-8"))
                .body(resource);
        return responseEntity;
    }

        /**
     * 根据属性名获取属性值
     *
     * @param fieldName 属性名
     * @param object    对象
     * @return 属性值
     * @author Zhang Haoyu
     */
    private String getFieldValueByFieldName(String fieldName, Object object) {
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            //设置对象的访问权限，保证对private的属性的访问
            field.setAccessible(true);
            return (String) field.get(object);
        } catch (Exception e) {
            return null;
        }
    }
}
